package com.jinzhi.jzdoor.training.controller;

import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.configconsts.wxconsts.LinkConfiggure;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.common.vo.WxPayConfig;
import com.jinzhi.common.vo.WxPayVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;


@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/traCourses")
public class TraCoursesController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayConfig wxPayConfig;
    @Autowired
    private ChainBase wxPayCoursesOrderChain;

    private static BigDecimal bigDecimal;

    static {
        bigDecimal = new BigDecimal(100);
    }


    /**
    * 培训门户端-学员购买课程微信支付接口（扫码支付）
    *
    * @Description: 培训门户端学员扫码微信支付；参数：wxpayVO虚拟实体（接收参数total_fee-支付金额，body-支付内容，trade_type-支付类型），课程订单id
    * @Param: [wxPayVo, courseOrderId]
    * @return: com.jinzhi.common.utils.ApiResult<?>
    * @Author: kl
    * @Date: 2020-04-28
    */
    @PostMapping("/wxPay")
    @Log("培训门户端-学员购买课程微信支付接口（扫码支付）")
    @ApiOperation(value = "培训门户端-学员购买课程微信支付接口（扫码支付）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    @Transactional
    public ApiResult<?> wxPay(@RequestHeader(value = TOKEN_TAG, required = false) String token,@Validated WxPayVo wxPayVo, String courseOrderId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        ApiResult apiResult = new ApiResult();
        try {
            //判断课程订单id是否为空
            if (null == courseOrderId || courseOrderId == "undefined") {
                return ApiResult.build(ApiEnumError.lackParameter.getCode(), "缺少参数:courseOrderId");
            }

            OrderDO orderDO = orderService.selectById(Long.parseLong(courseOrderId));

            //通过uuid生成商户id
            String out_trade_no = UUID.randomUUID().toString().replace("-", "");
            //生成32为随机数
            String randomStringBy = StringUtil.getRandomStringByLength(32);

            wxPayVo.setAppid(wxPayConfig.getTraAppid());//appid（微信公众号）
            wxPayVo.setMch_id(wxPayConfig.getMerNo());//商户id
            wxPayVo.setNotify_url(wxPayConfig.getCoursesOrderNotify());//回调地址
            wxPayVo.setSpbill_create_ip(wxPayConfig.getIp());//ip地址
            wxPayVo.setOut_trade_no(out_trade_no);
            wxPayVo.setNonce_str(randomStringBy);
            wxPayVo.setTotal_fee(new BigDecimal(orderDO.getOrderAmount().toString()).multiply(bigDecimal).setScale(0).toString());//支付金额
            wxPayVo.setLabel(WxPayLabelEnum.order.getTag());
            wxPayVo.setType(AppEnum.training.getTag());

            log.info("商户订单号:" + out_trade_no);

            //保存用户id至缓存，为后面回调提供
            EhCacheUtil.put(out_trade_no + ":courseOrderId", Long.parseLong(courseOrderId));

            //创建上下文
            Context context = new ContextBase();

            //微信支付对象
            context.put(LinkConfiggure.WX_PAY_VO, wxPayVo);
            //固定返回对象
            context.put(LinkConfiggure.API_RESULT, apiResult);
            //订单id
            context.put("courseOrderId", Long.parseLong(courseOrderId));
            //用户id
            context.put("user_id", user.getId());
            //商户订单号
            context.put("out_trade_no", out_trade_no);


            //开始链路
            wxPayCoursesOrderChain.execute(context);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new RuntimeException(e);
        }
        Map map = new HashMap();
        map.put("type", "wx");
        map.put("wx", apiResult);
        return ApiResult.success(map);
    }

    /**
    * 培训门户端-查询课程订单缴费状态
    *
    * @Description: 查询课程订单的缴费状态；参数：课程订单id
    * @Param: [courseOrderId]
    * @return: com.jinzhi.common.utils.ApiResult<?>
    * @Author: kl
    * @Date: 2020-04-28
    */
    @GetMapping("/selCoursesOrderState")
    @Log("培训门户端-查询课程订单缴费状态")
    @ApiOperation(value = "培训门户端-查询课程订单缴费状态", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    public ApiResult<?> selCoursesOrderState(String courseOrderId) {
        if(courseOrderId == null){
            return ApiResult.fail("参数缺失");
        }
        OrderDO orderDO = orderService.selectById(courseOrderId);
        if(orderDO != null){
            return ApiResult.success(orderDO.getState());
        }

        return ApiResult.fail();
    }
}
